package com.project.myPackage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.project.myPackage.common.R;
import com.project.myPackage.entity.Comments;
import com.project.myPackage.service.CommentsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(tags = "评论管理")
@Slf4j
@RestController
@RequestMapping("/")
public class CommentsController {
    @Autowired
    private CommentsService commentsService;

    @ApiOperation(value = "根据商品id获取商品所有评论信息")
    @RequestMapping("/getAllCommentsByProductId")
    public R<?> getAllCommentsByProductId(Integer product_id)
        {
        List< Map<String,Object> > list = commentsService.getList(product_id);
        if(list!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Map<String, Object> map : list) {
                Date createdAt = (Date) map.get("created_at");
                if (createdAt != null) {
                    map.put("created_at", sdf.format(createdAt));
                }
            }
            return R.success(list, "获取所有评论信息列表成功！");
        }else{
            return R.error("获取评论列表失败！");
        }
    }

    @ApiOperation(value = "新增评论信息")
    @PostMapping("/addComments")
    public R<?> addComments(@RequestBody Comments comments){
        boolean save = commentsService.save(comments);
        if(!save){
            return R.error("新增评论失败！");
        }
        return R.success("新增评论成功！");
    }

    @ApiOperation(value = "删除评论信息")
    @RequestMapping("/deleteComments")
    public R<?> deleteComments(Integer comment_id){
        boolean remove = commentsService.removeById(comment_id);
        if(!remove){
            return R.error("删除评论失败！");
        }
        return R.success("删除评论成功！");
    }

    @ApiOperation(value = "修改评论信息")
    @PostMapping("/updateComments")
    public R<?> updateComments(@RequestBody Comments comments){
        boolean update = commentsService.updateById(comments);
        if(!update){
            return R.error("修改评论失败！");
        }
        return R.success("修改评论成功！");
    }
}
